import random
import tkinter as tk
from tkinter import messagebox


class MinesweeperGame:
    def __init__(self, rows, cols, num_mines):
        self.rows = rows
        self.cols = cols
        self.num_mines = num_mines
        self.board = [[0] * cols for _ in range(rows)]
        self.visible_board = [[False] * cols for _ in range(rows)]
        self.mines = set()
        self.game_over = False

        self.window = tk.Tk()
        self.window.title("Minesweeper")
        self.buttons = [[None] * cols for _ in range(rows)]

        # 创建按钮网格
        for row in range(rows):
            for col in range(cols):
                button = tk.Button(
                    self.window,
                    width=3,
                    height=1,
                    command=lambda r=row, c=col: self.handle_click(r, c)
                )
                button.grid(row=row, column=col)
                self.buttons[row][col] = button

        self.generate_mines()
        self.calculate_counts()

    def generate_mines(self):
        mines = random.sample(range(self.rows * self.cols), self.num_mines)
        for mine in mines:
            row = mine // self.cols
            col = mine % self.cols
            self.board[row][col] = '*'
            self.mines.add((row, col))

    def calculate_counts(self):
        for row in range(self.rows):
            for col in range(self.cols):
                if self.board[row][col] != '*':
                    count = 0
                    for i in range(max(0, row - 1), min(self.rows, row + 2)):
                        for j in range(max(0, col - 1), min(self.cols, col + 2)):
                            if self.board[i][j] == '*':
                                count += 1
                    self.board[row][col] = count

    def handle_click(self, row, col):
        if self.game_over:
            return

        if (row, col) in self.mines:
            self.show_all_mines()
            self.show_game_over_message()
            return

        self.reveal_cell(row, col)

        if self.check_win():
            self.show_all_mines()
            self.show_win_message()

    def reveal_cell(self, row, col):
        if not self.visible_board[row][col]:
            self.visible_board[row][col] = True
            self.buttons[row][col].config(relief=tk.SUNKEN)

            if self.board[row][col] == 0:
                for i in range(max(0, row - 1), min(self.rows, row + 2)):
                    for j in range(max(0, col - 1), min(self.cols, col + 2)):
                        self.reveal_cell(i, j)
            elif self.board[row][col] != '*':
                self.buttons[row][col].config(text=str(self.board[row][col]))

    def show_all_mines(self):
        for row, col in self.mines:
            self.buttons[row][col].config(text='*', relief=tk.SUNKEN)

    def check_win(self):
        for row in range(self.rows):
            for col in range(self.cols):
                if not self.visible_board[row][col] and (row, col) not in self.mines:
                    return False

    def show_game_over_message(self):
        messagebox.showinfo("Game Over", "You stepped on a mine! Game Over.")
        self.game_over = True
        self.window.quit()

    def show_win_message(self):
        messagebox.showinfo("Congratulations", "You won the game!")
        self.game_over = True
        self.window.quit()

    def run(self):
        self.window.mainloop()

game = MinesweeperGame(10, 10, 10)
game.run()

# print("hello world")
#
# class test():
#     name = "test"
#     number = 0
#     def __init__(self):
#         self.name = "test1"
#         self.number = 1
#     def print(self):
#         print(self.name)
#         print(self.number)
#
# test1 = test()
# test1.name="张三"
# test1.number="001"
# test1.print()
# print(test1.name)
# print(test1.number)
# def bubble_sort(lst):
#     n = len(lst)
#     for i in range(n):
#         # 创建一个标志，表示这个列表在本次循环中是否已经排序好
#         already_sorted = True
#
#         # 开始从第一个元素到倒数第二个元素，逐个比较相邻两元素
#         for j in range(n - i - 1):
#             if lst[j] > lst[j + 1]:
#                 # 如果前一个元素大于后一个元素，交换它们（升序排序）
#                 lst[j], lst[j + 1] = lst[j + 1], lst[j]
#
#                 # 由于有元素被交换，所以列表尚未排序好
#                 already_sorted = False
#
#         # 如果列表在本次循环中已经排序好了，就没有必要再进行下一轮比较了
#         if already_sorted:
#             break
#
#     return lst
#
# # 测试冒泡排序函数
# numbers = [64, 34, 25, 12, 22, 11, 90]
# print(bubble_sort(numbers))
